//
//  MHScanViewController.m
//  ProjectforHDX
//
//  Created by HDX on 16/7/27.
//  Copyright © 2016年 H.DX. All rights reserved.
//

#import "MHScanViewController.h"
#import "FrostedView.h"
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>

#import "MHDefine.h"

enum {
    ALERTVIEWTAG = 1000,
};

@interface MHScanViewController ()<AVCaptureMetadataOutputObjectsDelegate, AVCaptureVideoDataOutputSampleBufferDelegate, UIAlertViewDelegate>
{
    AVCaptureVideoPreviewLayer *_captureVideoPreviewLayer;
    AVCaptureSession *_captureSession;
    UIView *scanninView;
    FrostedView *frostedView;
    
}

@end

@implementation MHScanViewController

#pragma mark - vc life cycle

- (void)viewDidLoad {
     [super viewDidLoad];
 
    self.labnav.text= [THMangerTool language:@"delivery.Barcode"];
    [self.labnav setFont:NavFontSize];
    [self.labnav setTextColor:[UIColor whiteColor]];
    BOOL cameraIsAvailable = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];

    
    NSString *mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    
    if (cameraIsAvailable && authStatus != AVAuthorizationStatusRestricted && authStatus != AVAuthorizationStatusDenied) {

        [self initCapture]; // 启动摄像头
        
    } else {

        [self alertWithTitle:@"温馨提示" msg:@"请在设置中打开摄像头权限" btnTitle:@"确定"];
    }
    
    scanninView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height)];
    
    [self.view addSubview:scanninView];
    
    
    CGRect cropRect = CGRectMake((scanninView.width-240)/2.f, 100, 240, 240);
    
     frostedView = [[FrostedView alloc] initWithTranslucentRect:cropRect];
    
    [scanninView addSubview:frostedView];
    
    UIView *footerView=[[UIView alloc] initWithFrame:CGRectMake(0, self.view.height-50-64, self.view.width, 50)];
    [footerView setBackgroundColor:[UtilCheck hexStringToColor:@"000000" alpha:1]];
    NSInteger count=2;
    CGFloat height=45;
    for (int i=0;i<count;i++) {
        
        RZCustomButtom *submit=[[RZCustomButtom alloc] init];
        [submit setFrame:CGRectMake((i+1)*(footerView.width-count*height)/(CGFloat)(count+1)+height*i, (footerView.height-height)/2.f, height, height)];
        [submit setTitle:@"扫码" forState:UIControlStateNormal];//确认
        if(i==1){
            [submit setTitle:@"封面" forState:UIControlStateNormal];//确认
        }
        [submit setTitleColor:[UtilCheck hexStringToColor:@"ffffff" alpha:1] forState:UIControlStateNormal];
        [submit setTitleColor:[UtilCheck hexStringToColor:@"00ff00" alpha:1] forState:UIControlStateSelected];
        [submit setTag:101+i];
        [submit addTarget:self action:@selector(touchClick:) forControlEvents:UIControlEventTouchUpInside];
        [submit.titleLabel setFont:CustomFont(14)];
        [footerView addSubview:submit];
    }
    [self.view addSubview:footerView];
    
    // Do any additional setup after loading the view.
}
-(void)touchClick:(RZCustomButtom*)sender{
    for(RZCustomButtom *btn in [sender.superview subviews]){
        btn.selected=NO;
    }
    sender.selected=!sender.selected;
        CGRect cropRect =CGRectZero;
    if(sender.tag==101)
    {
              cropRect = CGRectMake((scanninView.width-240)/2.f, 100, 240, 240);
    }
    else{
        cropRect = CGRectMake(30, 50, scanninView.width-60, (scanninView.width-60)*4/3.f);
    }
    [frostedView removeFromSuperview];
    frostedView = [[FrostedView alloc] initWithTranslucentRect:cropRect];
    
    [scanninView addSubview:frostedView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




#pragma mark - coding

- (void)initCapture {
    // capture session 数据的捕获,操作,输出
    _captureSession = [[AVCaptureSession alloc] init];
    // 捕获设备,这里是摄像头
    AVCaptureDevice *inputDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
//    AVCaptureDevice *inputDevice = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];

    
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    
    // 捕获设备的输入
    NSError *error = nil;
    AVCaptureDeviceInput *captureInput = [AVCaptureDeviceInput deviceInputWithDevice:inputDevice error:&error];
    
    if (!error) {
        // 正常捕获数据
        [_captureSession addInput:captureInput]; // 将输入添加到session上
    } else {
        // 捕获数据失败
        [self alertWithTitle:@"警告" msg:@"手机摄像头捕获图像出现故障,请检查权限设置!" btnTitle:@"确定"];
    }
    if (IOS7) {
        // 捕获到的数据的输出
        AVCaptureMetadataOutput *captureOutput = [[AVCaptureMetadataOutput alloc] init];
        [captureOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
        

        //深坑  这里的顺序是Y,X,H,W （0，0，1，1） Y表示扫描区域的Y值除以屏幕高度 H表示扫描区域的高度除以屏幕高度
        captureOutput.rectOfInterest = CGRectMake( 100/self.view.height,0, 240/self.view.height,1);
        
        
        [_captureSession setSessionPreset:AVCaptureSessionPresetHigh];
        [_captureSession addOutput:captureOutput];
 
        
   captureOutput.metadataObjectTypes = @[AVMetadataObjectTypeCode128Code,AVMetadataObjectTypeUPCECode,AVMetadataObjectTypeCode39Code,AVMetadataObjectTypeCode39Mod43Code,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode93Code,AVMetadataObjectTypePDF417Code,AVMetadataObjectTypeQRCode,AVMetadataObjectTypeAztecCode,AVMetadataObjectTypeInterleaved2of5Code,AVMetadataObjectTypeITF14Code,AVMetadataObjectTypeDataMatrixCode];
 
        if (!_captureVideoPreviewLayer) {
            _captureVideoPreviewLayer = [AVCaptureVideoPreviewLayer layerWithSession:_captureSession];
        }
        _captureVideoPreviewLayer.frame = self.view.bounds;
        _captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        [self.view.layer addSublayer:_captureVideoPreviewLayer];
        [_captureSession startRunning];
    }
}

- (void)alertWithTitle:(NSString *)titleStr msg:(NSString *)msgStr btnTitle:(NSString *)btnTitle {
    UIAlertView *av = [[UIAlertView alloc] initWithTitle:titleStr message:msgStr delegate:self cancelButtonTitle:btnTitle otherButtonTitles:nil, nil];
    av.tag = ALERTVIEWTAG;
    [av show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == ALERTVIEWTAG) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark -btn action 


#pragma mark -AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    
    if (metadataObjects.count > 0) {
        AVMetadataMachineReadableCodeObject *metadataObject = [metadataObjects objectAtIndex:0];
 
        self.rebackData(metadataObject.stringValue);
    }
    
    [_captureSession stopRunning];
    [self dismissViewControllerAnimated:YES completion:nil];
}


@end
